<template>
  <div class="course-import-container">
    <div class="header">
      <h2>课程批量导入</h2>
      <div class="actions">
        <el-button @click="$router.push('/back/courses')" icon="ArrowLeft">返回课程列表</el-button>
      </div>
    </div>

    <el-card class="import-card">
      <template #header>
        <div class="card-header">
          <span>上传文件</span>
          <el-button type="primary" @click="downloadTemplate">下载导入模板</el-button>
        </div>
      </template>
      <div class="upload-area">
        <el-upload
          ref="uploadRef"
          class="upload-wrapper"
          drag
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-exceed="handleExceed"
          :before-remove="handleRemove"
          accept=".csv,.xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处，或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              请上传CSV或Excel格式文件，大小不超过10MB<br>
              表头格式：标题,标题链接,机构,难度,学时,热度,语言,开课日期,副标题,学科,平台
            </div>
          </template>
        </el-upload>
        <div class="upload-actions" v-if="fileList.length > 0">
          <el-button type="primary" @click="importFile">导入文件</el-button>
          <el-button @click="clearFile">清除文件</el-button>
        </div>
      </div>
    </el-card>

    <el-card v-if="parsedData.length > 0" class="preview-card">
      <template #header>
        <div class="card-header">
          <span>数据预览 (共 {{ parsedData.length }} 条)</span>
          <div class="preview-actions">
            <el-button type="success" :disabled="selectedRows.length === 0" @click="importSelectedData">
              导入选中数据 ({{ selectedRows.length }})
            </el-button>
            <el-button :disabled="selectedRows.length === parsedData.length" @click="selectAllData">全选</el-button>
            <el-button :disabled="selectedRows.length === 0" @click="deselectAllData">取消全选</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="tableLoading"
        :data="parsedData"
        border
        style="width: 100%"
        max-height="600"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="#" width="60" />
        <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="courseUrl" label="链接" min-width="180" show-overflow-tooltip />
        <el-table-column prop="institution" label="机构" width="120" show-overflow-tooltip />
        <el-table-column prop="difficulty" label="难度" width="100">
          <template #default="{ row }">
            <el-tag :type="getDifficultyType(row.difficulty)">
              {{ row.difficulty }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="学时" width="100" />
        <el-table-column prop="language" label="语言" width="120" show-overflow-tooltip />
        <el-table-column prop="startDate" label="开课日期" width="120" />
        <el-table-column prop="subject" label="学科" width="120" />
        <el-table-column prop="platform" label="平台" width="120" />
        <el-table-column prop="categoryName" label="分类" width="120">
          <template #default="{ row }">
            <el-select v-model="row.categoryId" placeholder="选择分类" size="small" style="width: 100%">
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'pending'" type="info">等待导入</el-tag>
            <el-tag v-else-if="row.status === 'success'" type="success">导入成功</el-tag>
            <el-tag v-else-if="row.status === 'error'" type="danger">导入失败</el-tag>
            <el-tag v-else type="warning">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="danger" size="small" @click="removeRow(row)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="importResultVisible"
      title="导入结果"
      width="600px"
    >
      <div class="import-result">
        <el-result
          :icon="importResult.success ? 'success' : 'error'"
          :title="importResult.success ? '导入成功' : '导入失败'"
          :sub-title="importResult.message"
        >
          <template #extra>
            <div class="result-stats">
              <div class="stat-item">
                <div class="stat-label">总计</div>
                <div class="stat-value">{{ importResult.total }}</div>
              </div>
              <div class="stat-item success">
                <div class="stat-label">成功</div>
                <div class="stat-value">{{ importResult.successCount }}</div>
              </div>
              <div class="stat-item error">
                <div class="stat-label">失败</div>
                <div class="stat-value">{{ importResult.failureCount }}</div>
              </div>
            </div>
            <el-button type="primary" @click="importResultVisible = false">确定</el-button>
          </template>
        </el-result>
      </div>
    </el-dialog>

    <el-dialog
      v-model="parseProgressVisible"
      title="操作进度"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="parse-progress">
        <el-progress :percentage="parseProgress" :stroke-width="18" />
        <div class="progress-info">
          <div class="progress-status">
            <span v-if="parseProgress < 100">{{ progressStatus }}</span>
            <span v-else class="completed">处理完成！</span>
          </div>
          <div class="progress-percentage">{{ parseProgress }}%</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Upload, ArrowLeft } from '@element-plus/icons-vue';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import request from '@/utils/request';

// 状态变量
const uploadRef = ref(null);
const fileList = ref([]);
const parsedData = ref([]);
const selectedRows = ref([]);
const tableLoading = ref(false);
const categories = ref([]);
const defaultCategoryId = ref(null);
const importResultVisible = ref(false);
const parseProgress = ref(0);
const parseProgressVisible = ref(false);
const progressStatus = ref('准备中...');
const importResult = reactive({
  success: false,
  message: '',
  total: 0,
  successCount: 0,
  failureCount: 0,
  failures: []
});

// 默认封面图片
const defaultCoverImage = 'https://img1.baidu.com/it/u=2740508675,2277159667&fm=253&fmt=auto&app=138&f=JPEG?w=758&h=500';

// 获取分类列表
const fetchCategories = async () => {
  try {
    await request.get('/category/all', null, {
      showDefaultMsg: false,
      onSuccess: (res) => {
        categories.value = res;
        if (res.length > 0) {
          defaultCategoryId.value = res[0].id;
        }
      }
    });
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
};

// 处理文件上传
const handleFileChange = (file) => {
  fileList.value = [file];
};

// 处理文件超出限制
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件');
};

// 处理文件删除
const handleRemove = () => {
  clearFile();
  return true;
};

// 清除文件
const clearFile = () => {
  fileList.value = [];
  parsedData.value = [];
  selectedRows.value = [];
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

// 下载导入模板
const downloadTemplate = () => {
  const headers = ['标题', '标题链接', '机构', '难度', '学时', '热度', '语言', '开课日期', '副标题', '学科', '平台'];
  const data = [
    ['自动驾驶汽车', 'http://www.mooc.cn/course/14162.html', '多伦多大学', '难（高级）', '2 个月', '热度 518', '英语', '2月15日', '专项课程', '计算机', 'Coursera'],
    ['学习编程：撰写高质量代码', 'http://www.mooc.cn/course/14161.html', '多伦多大学', '简单（初级）', '20 个小时', '热度 436', '英语', '2月15日', '', '计算机', 'Coursera']
  ];
  
  const worksheet = XLSX.utils.aoa_to_sheet([headers, ...data]);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '课程导入模板');
  
  // 生成Excel文件并下载
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  saveAs(blob, '课程导入模板.xlsx');
};

// 导入文件
const importFile = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先上传文件');
    return;
  }

  const confirmResult = await ElMessageBox.confirm(
    '确定要上传并导入文件吗？服务器将处理文件并导入数据',
    '确认导入',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).catch(() => false);

  if (!confirmResult) return;

  const file = fileList.value[0].raw;
  tableLoading.value = true;
  parseProgressVisible.value = true;
  parseProgress.value = 0;
  progressStatus.value = '准备上传文件...';

  try {
    // 直接使用axios而不是封装的request，确保文件上传正确
    const formData = new FormData();
    formData.append('file', file);
    if (defaultCategoryId.value) {
      formData.append('defaultCategoryId', defaultCategoryId.value);
    }
    
    console.log('[导入] FormData内容:', file.name, defaultCategoryId.value);
    console.log('[导入] 请求地址:', '/api/course/import');
    
    // 使用axios直接上传
    const axios = require('axios');
    const response = await axios.post('/api/course/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 50) / progressEvent.total);
        updateProgress(10 + percentCompleted, `上传进度: ${percentCompleted}%`);
        console.log(`[导入] 上传进度: ${percentCompleted}%`);
      }
    });
    
    console.log('[导入] 服务器响应:', response);
    
    // 检查响应
    if (response.data && response.data.code === "200") {
      const res = response.data.data;
      
      // 显示导入结果
      updateProgress(90, '处理解析结果...');
      
      importResult.success = res.failureCount === 0;
      importResult.message = res.failureCount === 0 
        ? '所有数据导入成功' 
        : `部分数据导入失败，请查看详情`;
      importResult.total = res.totalRows;
      importResult.successCount = res.successCount;
      importResult.failureCount = res.failureCount;
      importResult.failures = res.failures || [];

      updateProgress(100, '导入完成！');
      
      ElMessage.success(`成功导入 ${res.successCount} 条课程数据`);
      
      // 延迟关闭进度条，让用户看到完成状态
      setTimeout(() => {
        parseProgressVisible.value = false;
        tableLoading.value = false;
        importResultVisible.value = true;
      }, 800);
    } else {
      throw new Error('服务器响应异常: ' + (response.data ? response.data.msg : '未知错误'));
    }
  } catch (error) {
    console.error('[导入] 错误:', error);
    ElMessage.error(`导入失败: ${error.message || '未知错误'}`);
    parseProgressVisible.value = false;
    tableLoading.value = false;
  }
};

// 辅助函数：更新进度条状态
const updateProgress = (value, status) => {
  parseProgress.value = value;
  progressStatus.value = status;
  console.log(`[导入] 进度: ${value}%, ${status}`);
};

// 获取难度类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case '初级':
      return 'success';
    case '中级':
      return 'warning';
    case '高级':
      return 'danger';
    default:
      return 'info';
  }
};

// 选择/取消选择所有数据
const selectAllData = () => {
  const table = document.querySelector('.el-table__body-wrapper .el-table__body');
  if (table) {
    const checkboxes = table.querySelectorAll('.el-table__row .el-checkbox input');
    checkboxes.forEach(checkbox => {
      if (!checkbox.checked) {
        checkbox.click();
      }
    });
  }
};

const deselectAllData = () => {
  const table = document.querySelector('.el-table__body-wrapper .el-table__body');
  if (table) {
    const checkboxes = table.querySelectorAll('.el-table__row .el-checkbox input');
    checkboxes.forEach(checkbox => {
      if (checkbox.checked) {
        checkbox.click();
      }
    });
  }
};

// 处理选择行变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 删除某一行
const removeRow = (row) => {
  try {
    // 如果在选中行中，先从选中行中移除
    const selectedIndex = selectedRows.value.findIndex(item => item.index === row.index);
    if (selectedIndex !== -1) {
      selectedRows.value.splice(selectedIndex, 1);
    }
    
    // 从数据列表中移除
    const index = parsedData.value.findIndex(item => item.index === row.index);
    if (index !== -1) {
      parsedData.value.splice(index, 1);
      
      // 重新编号
      parsedData.value.forEach((item, i) => {
        item.index = i + 1;
      });
      
      ElMessage.success('已移除该行数据');
    } else {
      ElMessage.warning('未找到要删除的数据行');
    }
  } catch (error) {
    console.error('删除行数据失败:', error);
    ElMessage.error('删除行数据失败');
  }
};

// 导入选中数据
const importSelectedData = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要导入的数据');
    return;
  }

  const confirmResult = await ElMessageBox.confirm(
    `确定要导入选中的 ${selectedRows.value.length} 条数据吗？`,
    '确认导入',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).catch(() => false);

  if (!confirmResult) return;

  tableLoading.value = true;
  
  // 显示导入进度对话框
  parseProgressVisible.value = true;
  parseProgress.value = 0;
  progressStatus.value = '准备导入数据...';
  
  try {
    const allCoursesToImport = selectedRows.value.map(row => {
      return {
        title: row.title,
        subtitle: row.subtitle || '',
        description: `${row.title} - ${row.institution}提供的${row.difficulty}课程`,
        courseUrl: row.courseUrl,
        coverImage: row.coverImage,
        institution: row.institution,
        difficulty: row.difficulty,
        duration: row.duration,
        heatScore: row.heatScore,
        language: row.language,
        startDate: row.startDate,
        subject: row.subject,
        platform: row.platform,
        categoryId: row.categoryId,
        viewCount: 0
      };
    });
    
    // 设置结果统计
    const allResults = {
      successes: [],
      failures: [],
      totalRows: allCoursesToImport.length,
      successCount: 0,
      failureCount: 0
    };
    
    // 分批导入，避免请求超时
    const batchSize = 20; // 每批导入20条数据
    const totalBatches = Math.ceil(allCoursesToImport.length / batchSize);
    
    progressStatus.value = `开始导入数据，共 ${totalBatches} 批...`;
    ElMessage.info(`开始导入数据，将分${totalBatches}批进行，请耐心等待...`);
    
    for (let i = 0; i < totalBatches; i++) {
      parseProgress.value = Math.floor((i / totalBatches) * 100);
      
      // 获取当前批次的数据
      const start = i * batchSize;
      const end = Math.min(start + batchSize, allCoursesToImport.length);
      const currentBatch = allCoursesToImport.slice(start, end);
      
      // 更新状态消息
      progressStatus.value = `正在导入第 ${i+1}/${totalBatches} 批（${start+1}-${end}/${allCoursesToImport.length}）`;
      ElMessage.info(`正在导入第 ${i+1}/${totalBatches} 批数据（${start+1}-${end}/${allCoursesToImport.length}）`);
      
      try {
        // 直接使用request工具调用API1
        const res = await request.post('/course/batch', { courses: currentBatch }, {
          showDefaultMsg: false,
          timeout: 60000, // 增加超时时间到60秒
          onError: (error) => {
            console.error(`批次请求错误:`, error);
          },
          onSuccess: (res) => {
            console.log(`批次请求成功:`, res);
          }
        });
        
        // 合并结果
        allResults.successes.push(...(res.successes || []));
        allResults.failures.push(...(res.failures || []));
        allResults.successCount += (res.successCount || 0);
        allResults.failureCount += (res.failureCount || 0);
        
        // 更新行状态
        if (res.successes) {
          res.successes.forEach(id => {
            const row = selectedRows.value.find(r => r.title === id);
            if (row) {
              row.status = 'success';
            }
          });
        }
        
        if (res.failures) {
          res.failures.forEach(failure => {
            const row = selectedRows.value.find(r => r.title === failure.id);
            if (row) {
              row.status = 'error';
              row.errorMessage = failure.reason;
            }
          });
        }
        
        // 给一点延迟，避免浏览器卡死
        await new Promise(resolve => setTimeout(resolve, 100));
        
      } catch (error) {
        console.error(`批次 ${i+1} 导入失败:`, error);
        ElMessage.error(`第 ${i+1} 批数据导入失败，将继续处理剩余批次`);
        
        // 将当前批次标记为失败
        currentBatch.forEach(course => {
          const row = selectedRows.value.find(r => r.title === course.title);
          if (row) {
            row.status = 'error';
            row.errorMessage = '网络请求失败';
          }
          
          allResults.failures.push({
            id: course.title,
            reason: '网络请求失败: ' + (error.message || '未知错误')
          });
          allResults.failureCount++;
        });
      }
    }
    
    parseProgress.value = 100;
    progressStatus.value = '导入完成！';
    
    // 显示导入结果
    importResult.success = allResults.failureCount === 0;
    importResult.message = allResults.failureCount === 0 
      ? '所有数据导入成功' 
      : `部分数据导入失败，请查看详情`;
    importResult.total = allResults.totalRows;
    importResult.successCount = allResults.successCount;
    importResult.failureCount = allResults.failureCount;
    importResult.failures = allResults.failures;
    
    // 延迟显示结果对话框，让用户看到完成进度
    setTimeout(() => {
      parseProgressVisible.value = false;
      importResultVisible.value = true;
      
      if (allResults.successCount > 0) {
        ElMessage.success(`成功导入 ${allResults.successCount} 条数据`);
      }
    }, 1000);
    
  } catch (error) {
    console.error('导入过程中发生错误:', error);
    ElMessage.error(`导入过程中发生错误: ${error.message || '未知错误'}`);
    parseProgressVisible.value = false;
  } finally {
    tableLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  fetchCategories();
});
</script>

<style lang="scss" scoped>
.course-import-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: var(--el-text-color-primary);
    }
  }

  .import-card, .preview-card {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .upload-area {
    display: flex;
    flex-direction: column;
    align-items: center;

    .upload-wrapper {
      width: 100%;
    }

    .upload-actions {
      margin-top: 20px;
      display: flex;
      gap: 10px;
    }
  }

  .preview-actions {
    display: flex;
    gap: 10px;
  }

  .parse-progress {
    padding: 20px 0;

    .progress-info {
      display: flex;
      justify-content: space-between;
      margin-top: 15px;
      font-size: 14px;
      color: var(--el-text-color-secondary);

      .progress-status {
        .completed {
          color: var(--el-color-success);
          font-weight: bold;
        }
      }

      .progress-percentage {
        font-weight: bold;
      }
    }
  }

  .import-result {
    .result-stats {
      display: flex;
      justify-content: center;
      gap: 30px;
      margin-bottom: 20px;

      .stat-item {
        text-align: center;
        padding: 10px 20px;
        border-radius: 4px;
        background-color: var(--el-fill-color-light);

        &.success {
          color: var(--el-color-success);
        }

        &.error {
          color: var(--el-color-danger);
        }

        .stat-label {
          font-size: 14px;
          margin-bottom: 5px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: bold;
        }
      }
    }
  }
}
</style> 